package com.nuoyuan.wx.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nuoyuan.wx.common.utils.GsonUtil;
import com.nuoyuan.wx.vo.PageVo;
import com.nuoyuan.wx.vo.UserVo;
import com.nuoyuan.wx.common.aop.ProxyExceptionReturn;
import com.nuoyuan.wx.common.dto.BaseRespDto;
import com.nuoyuan.wx.dao.mapper.UserMapper;
import com.nuoyuan.wx.dao.po.UserPo;
import com.nuoyuan.wx.service.helper.UserBeanHepler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Package com.nuoyuan.wx.service
 * @ClassName UserService
 * @Description TODO
 * @Author linus
 * @Date 2020-02-21 15:06
 * @Version 1.0
 **/
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;


    @ProxyExceptionReturn
    public BaseRespDto add(UserVo vo) {
        userMapper.insert(UserBeanHepler.toPo(vo));
        return BaseRespDto.buildSuccResp();
    }

    @ProxyExceptionReturn
    public BaseRespDto<UserVo> getDetail(UserVo vo) {
        Wrapper<UserPo> queryWrapper = new QueryWrapper<>();
        ((QueryWrapper<UserPo>) queryWrapper).eq("user_id", vo.getUserId());
        UserPo po = userMapper.selectOne(queryWrapper);

        BaseRespDto resp = BaseRespDto.buildSuccResp();
        if(po != null) {
            resp.setData(UserBeanHepler.toVo(po));
        }

        return resp;
    }

    @ProxyExceptionReturn
    public BaseRespDto update(UserVo vo) {
        Wrapper<UserPo> updateWrapper = new UpdateWrapper<>();
        ((UpdateWrapper<UserPo>) updateWrapper).eq("user_id", vo.getUserId());
        userMapper.update(UserBeanHepler.toPo(vo), updateWrapper);
        return BaseRespDto.buildSuccResp();
    }



    @ProxyExceptionReturn
    public BaseRespDto<PageVo<UserVo>> getList(PageVo page) {
        Wrapper<UserPo> queryWrapper = new QueryWrapper<>();
        ((QueryWrapper<UserPo>) queryWrapper).orderByDesc("user_id");
        IPage p = new Page();
        p.setCurrent(page.getPageNo());
        p.setSize(page.getPageSize());
        IPage<UserPo> pages = userMapper.selectPage(p, queryWrapper);

        BaseRespDto resp = BaseRespDto.buildSuccResp();
        if(null == pages || CollectionUtils.isEmpty(pages.getRecords())) {
            PageVo emptyP = new PageVo<>();
            emptyP.setItems(new ArrayList());
            resp.setData(emptyP);
            return resp;
        }
        List<UserPo> pos = pages.getRecords();
        page.setCount(pages.getTotal());
        page.setItems(UserBeanHepler.toVos(pos));

        resp.setData(page);
        return resp;
    }



}
